package io.github.yidasanqian.controller;

import io.github.yidasanqian.domain.Goods;
import io.github.yidasanqian.dto.GoodsCategoryDTO;
import io.github.yidasanqian.dto.GoodsDTO;
import io.github.yidasanqian.service.GoodsService;
import io.github.yidasanqian.vo.EasyUIVO;
import io.github.yidasanqian.vo.GoodsCategoryVO;
import io.github.yidasanqian.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Linyu Chen
 */
@Slf4j
@RequestMapping("goods")
@Controller
public class GoodsController {

    @Resource
    private GoodsService goodsService;

    @PostMapping("/save")
    @ResponseBody
    public ResultVO addGoods(Goods goods, String desc) {
        int row;
        try {
            row = goodsService.addGoods(goods, desc);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultVO.buildErrorResult(0, "添加商品出现异常", null);
        }
        return ResultVO.buildSuccessResult(0, "success", row);
    }

    @GetMapping("/{goodsId}")
    @ResponseBody
    public ResultVO getGoods(@PathVariable Long goodsId) {
        Goods goods = goodsService.findGoodsById(goodsId);
        log.debug("goods <== {}", goods.toString());
        return ResultVO.buildSuccessResult(0, "success", goods);
    }

    @GetMapping("/list")
    @ResponseBody
    public EasyUIVO findAll(Integer page, Integer rows) {
        GoodsDTO goodsDTO = goodsService.findAll(page, rows);
        log.debug("goodsDTOList Size : {}", goodsDTO.getGoodsVOList().size());
        EasyUIVO easyUIVO = new EasyUIVO();
        easyUIVO.setRows(goodsDTO.getGoodsVOList());
        easyUIVO.setTotal(goodsDTO.getTotal());
        return easyUIVO;
    }

    @GetMapping("/category/list")
    @ResponseBody
    public List<GoodsCategoryVO> queryGoodsCategoryList(@RequestParam(name = "id", defaultValue = "0") Long parentId) {
        GoodsCategoryDTO goodsCategoryDTO = goodsService.queryGoodsCategoryNodeList(parentId);
        List<GoodsCategoryVO> goodsCategoryVOList = goodsCategoryDTO.getGoodsCategoryVOList();
        return goodsCategoryVOList;
    }
}
